import axios from 'axios';
import jwt_decode from 'jwt-decode';
import { message } from 'antd'
import qs from 'qs';

//登录 无token传参 获取res的token 
const newService = () => {
  const tokenConfig = {
    timeout: 1000000,
    headers: {
      'Authorization': ''
    }, // 请求超时限制
  }
  const token=localStorage.getItem('Token');
  if (token) {
    tokenConfig['headers']['Authorization'] = 'Bearer ' + token;
  }
  const service = axios.create(tokenConfig);
  service.interceptors.request.use(config => {
    const localToken = localStorage.getItem('Token');
    if (localToken) {
      const currentTime = Date.now() / 1000;
      const oldToken = jwt_decode(localToken);
      console.log(oldToken.exp, currentTime)
      if ((oldToken.exp - 17819802) < currentTime) {//过期
        localStorage.removeItem('Token');
        localStorage.removeItem('userLevel');
        alert('登录过期，请重新登录')
        window.location.href = "/login";
      }
    }
    if (config.method === 'post') {
      config.transformRequest = function (data, headers) {
        if (typeof (data) === 'object') {
          return qs.stringify(data);
        }
        else {
          return data
        }
      }
    } else {
      config.params = { ...config.params };
    }

    return config;
  }, error => {
    // 请求错误处理
    Promise.reject(error);
  });
  service.interceptors.response.use(res => {
    if (res.status === 200) {
      message.success(res.data.metaData.message);
      if (res.data.token) {
        console.log('res.data.token')
        if (localStorage.getItem('Token')) {
          localStorage.removeItem('Token');
          localStorage.setItem('Token', res.data.token);
        }
        else if (!localStorage.getItem('Token')) {
          localStorage.setItem('Token', res.data.token);
        }

      }
      return res;
    }
    else {
      alert('权限不够，重新登录')
      window.location.href = "/login";
      return res
    }
  });
  return service;
}
export default newService;